﻿using System;
using System.Threading.Tasks;
using Coravel.Invocable;
using CRM.Services.Email;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace CRM.Jobs
{
    /// <summary>
    /// 标记邮件已读事件
    /// </summary>
    public class EmailReadEvent : IInvocable, IInvocableWithPayload<EmailReadEventParam>
    {
        private readonly IServiceProvider _provider;
        private readonly ILogger<EmailReadEvent> _logger;

        public EmailReadEvent(IServiceProvider provider, ILogger<EmailReadEvent> logger)
        {
            _provider = provider;
            _logger = logger;
        }

        public async Task Invoke()
        {
            if (Payload.Id == 0 || string.IsNullOrEmpty(Payload.Email))
                return;
            // if (!await _cache.HasAsync($"{Payload.Id}_{Payload.Email}"))
            // {
            //     _logger.LogTrace("营销任务[{Id}]邮箱[{Email}]缓存不存在", Payload.Id, Payload.Email);
            //     return;
            // }
                
            var emailMarketingService =
                _provider.CreateScope().ServiceProvider.GetRequiredService<EmailMarketingService>();
            await emailMarketingService.MarkEmailRead(Payload.Id, Payload.Email);
            _logger.LogInformation("邮箱[{Email}]阅读了营销任务[{Id}]的邮件", Payload.Email, Payload.Id);
        }

        public EmailReadEventParam Payload { get; set; }
    }

    public class EmailReadEventParam
    {
        public int Id { get; }
        public string Email { get; }

        public EmailReadEventParam(string id, string email)
        {
            Id = int.TryParse(id, out var i) ? i : 0;
            Email = email is not null
                ? System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(email))
                : string.Empty;
        }
    }
}